const connect = require('connect')

function logger(req, res, next) {
  console.log('%s %s', req.method, req.url)
  next()
}

function hello(req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.end('hello world')
}

function authenticateWithDatabase(user, pass, cb) {
  console.log({user, pass})
  if (user === 'admin' && pass === 'admin') {
    cb()
    return
  }

  cb(new Error('Incorrect username or password'))
}

// Basic auth
function restrict(req, res, next) {
  const authorization = req.headers.authorization
  if (!authorization) return next(new Error('Unauthorized'))

  const parts = authorization.split(' ')
  console.log(parts)
  const scheme = parts[0]
  const auth = new Buffer(parts[1], 'base64').toString().split(':')
  console.log(auth)
  const user = auth[0]
  const pass = auth[1]

  authenticateWithDatabase(user, pass, (err) => {
    if (err) return next(err)
    next()
  })
}

function admin(req, res, next) {
  switch (req.url) {
    case '/':
      res.end('try /users')
      break
    case '/users':
      res.setHeader('Content-Type', 'application/json')
      res.end(JSON.stringify(['tobi', 'loki', 'jane']))
      break
    default:
      next(new Error('not found'))
  }
}

connect()
  .use(logger)
  .use('/admin', restrict)
  .use('/admin', admin)
  .use(hello)
  .listen(3000)

/*
curl --user admin:admin http://localhost:3000/admin/users
 */
